package com.example.pro1.service.zhao.wxapplets.impl;
import com.example.pro1.config.zhao.WxAppletsConfig;
import com.example.pro1.enums.wxapplets.login;
import com.example.pro1.service.zhao.wxapplets.WxAppletsLogin;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class WxAppletsLoginImpl implements WxAppletsLogin {
    @Resource
    private WxAppletsConfig wxAppletsConfig;

    @Override
    public String login(String code) throws Exception {

        CloseableHttpClient httpClient = HttpClients.createDefault() ;

        String url=String.format(login.LOGIN_FOROP.getType(),wxAppletsConfig.getAppID(),wxAppletsConfig.getAppSecret(),code);
        url=wxAppletsConfig.getMain().concat(url);

        log.info("url===>{}",url);
        HttpGet httpGet=new HttpGet(url);
        httpGet.setHeader("Accept", "application/json");

        CloseableHttpResponse response= httpClient.execute(httpGet);

        String bodyAsString =EntityUtils.toString(response.getEntity());
        int statusCode =response.getStatusLine().getStatusCode();
        try {
            if (statusCode==200)//OK!
                log.info("微信登录调用成功返回");
            else
            {
                if (statusCode==204)
                    log.info("微信登录调用成功返回");
                else
                    log.warn("微信登录回调失败，响应码= "+statusCode+",返回结果 = "+bodyAsString);
            }
            return bodyAsString;
        }finally {
            response.close();
        }



    }
}
